<?php
class Mageex_AdvanceSeo_Block_Review_Product_View_List extends Mage_Review_Block_Product_View
{
    protected $_forceHasOptions = false;

    public function getProductId()
    {
        return Mage::registry('product')->getId();
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        if ($toolbar = $this->getLayout()->getBlock('product_review_list.toolbar')) {
            $toolbar->setCollection($this->getReviewsCollection());
            $this->setChild('toolbar', $toolbar);
        }

        return $this;
    }

    protected function _beforeToHtml()
    {
        $this->getReviewsCollection()
            ->load()
            ->addRateVotes();
        return parent::_beforeToHtml();
    }
	
    public function getReviewUrl($id)
    {
		if(Mage::helper('advanceseo/config')->isRewriteReview()){
		
			$productName 	= Mage::helper('advanceseo/data')->stringConvert($this->getProduct()->getName());
			$urlrewriteModel = Mage::getModel('core/url_rewrite');
            $dataRewrite = array();
            
            $targetPath = 'review/product/view/id/'.$id .'/'; 

            //get review config path
			$cfpath =  Mage::helper('advanceseo/config')->getPathReview();
			
			//get review title
			$review = Mage::getModel('review/review')->load($id);
			$reviewTitle = Mage::helper('advanceseo/data')->stringConvert($review->getTitle());
			
			//return rewrite path
            $requestPath = $productName.'/'.$cfpath.'/'.$reviewTitle.Mage::helper('advanceseo/data')->getSuffix();        
              
            $rewriteCollection = $urlrewriteModel->getCollection()
                                  ->addFieldToFilter('target_path', $targetPath);
								  
            if(count($rewriteCollection)==0){
                $dataRewrite['store_id'] 		= Mage::app()->getStore()->getId();
                $dataRewrite['id_path'] 		= $targetPath;
                $dataRewrite['target_path'] 	= $targetPath;
                $dataRewrite['request_path'] 	= $requestPath;
                $dataRewrite['is_system'] 		= 0;
                
                try {
                    $urlrewriteModel->setData($dataRewrite);
                    $urlrewriteModel->save();
                   
                }
                catch (Exception $e) {
						
                }
            }else{
				//If targetpath existed
				//Update core_url_rewrite
				foreach($rewriteCollection as $rewrite){
					$idCoreUrl 		= $rewrite->getId();
					$requestPaths 	= $rewrite->getRequestPath();
					break;
				}
				
				if($requestPaths != $requestPath){
					$data['request_path'] = $requestPath;
					$urlrewriteModel->load($idCoreUrl)->addData($data);
					$urlrewriteModel->setId($idCoreUrl)->save();
				}
			 }
             return Mage::getBaseUrl().$requestPath;
		}else{
			return Mage::getUrl('*/*/view', array('id' => $id));
		}
		
    }
}
